<?php

namespace app\api\controller\qixing;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\library\Upload;
use fast\Random;
use fast\Http;
use think\Config;
use think\Validate;
use think\Db;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile','thirdpParameter' , 'third'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }

    /**
     * 会员中心
     */
    public function index()
    {
        $this->success('', ['welcome' => $this->auth->nickname]);
    }

    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $user = $this->auth->getUserinfo();
            $data = ['userinfo' => $user];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email    邮箱
     * @param string $mobile   手机号
     * @param string $code     验证码
     */
    public function register()
    {
        $username = $this->request->post('email');
        $password = $this->request->post('password');
        $email = $this->request->post('email');
        $mobile = $this->request->post('mobile');
        $code = $this->request->post('code');
        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        // if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
        //     $this->error(__('Mobile is incorrect'));
        // }
        //$ret = Sms::check($mobile, $code, 'register');
        // if (!$ret) {
        //     $this->error(__('Captcha is incorrect'));
        // }
        $result = Ems::check($email, $code, 'register');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $ret = $this->auth->register($username, $password, $email, $mobile, []);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 注销登录
     * @ApiMethod (POST)
     */
    public function logcancellation()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $userid = $this->auth->id;
        $code = $this->request->post('code');
        $email = $this->auth->email;
        $result = Ems::check($email, $code, 'cancellation');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        // $cycling = Db::name('cycling')->where(['userid'=>$userid,'state'=>['in','1,2']])->find();
        // if ($cycling) {
        //    $this->error(__('Unfinished cycling'));
        // }
        $whereOr = ['touid'=>$userid,'status'=>['in','0,1']];
        $tryride = Db::name('tryride')->where(['applyuid'=>$userid,'status'=>['in','0,1']])
        ->whereOr(function ($query) use ($whereOr) {
            $query->where($whereOr);
        })->find();
        if ($tryride) {
           $this->error(__('Unfinished try to ride'));
        }
        //删除骑行、试骑数据
        Db::name('cycling_search')->where('userid',$userid)->delete();
        Db::name('user_cycling')->where('uid',$userid)->delete();
        Db::name('cycling')->where('userid',$userid)->delete();
        Db::name('qixing_third')->where('user_id',$userid)->delete();
        Db::name('user_privateline')->where('userid',$userid)->delete();
        $this->auth->delete($userid);
        $this->auth->logout();
        $this->success(__('Cancellation successful'));
    }

    public function uploadavatar(){
        Config::set('default_return_type', 'json');
        //必须设定cdnurl为空,否则cdnurl函数计算错误
        Config::set('upload.cdnurl', '');
        $type = $this->request->post("type");
        $chunkid = $this->request->post("chunkid");
        if ($chunkid) {
            if (!Config::get('upload.chunking')) {
                $this->error(__('Chunk file disabled'));
            }
            $action = $this->request->post("action");
            $chunkindex = $this->request->post("chunkindex/d");
            $chunkcount = $this->request->post("chunkcount/d");
            $filename = $this->request->post("filename");
            $method = $this->request->method(true);
            if ($action == 'merge') {
                $attachment = null;
                //合并分片文件
                try {
                    $upload = new Upload();
                    $attachment = $upload->merge($chunkid, $chunkcount, $filename);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $user = $this->auth->getUser();
                $user->avatar = $attachment->url;
                $user->save();
                $this->success('', ['fullurl' => cdnurl($attachment->url, true)]);
            } elseif ($method == 'clean') {
                //删除冗余的分片文件
                try {
                    $upload = new Upload();
                    $upload->clean($chunkid);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success();
            } else {
                //上传分片文件
                //默认普通上传文件
                $file = $this->request->file('file');
                try {
                    $upload = new Upload($file);
                    $upload->chunk($chunkid, $chunkindex, $chunkcount);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success();
            }
        } else {
            $attachment = null;
            //默认普通上传文件
            if ($type=='base64') {
                $file = $this->request->post('file');
                $attachmenturl = $this->saveBase64($file);
            }else{
                $file = $this->request->file('file');
                try {
                    $upload = new Upload($file);
                    $attachment = $upload->upload();
                    $attachmenturl = $attachment->url;
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
            }
            $user = $this->auth->getUser();
            $user->avatar = $attachmenturl;
            $user->save();
            $this->success('', ['fullurl' => cdnurl($attachmenturl, true)]);
        }
    }

    public function saveBase64($base64_img)
    {
        //目录的upload文件夹下
        $up_dir = ROOT_PATH . "public/uploads/".date('Ymd', time()) . "/";  //创建目录
        if(!file_exists($up_dir)){
            mkdir($up_dir,0777,true);
        }
        if(preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_img, $result)){
            $type = $result[2];
            if(in_array($type,array('pjpeg','jpeg','jpg','gif','bmp','png'))){
                $name = \fast\Random::alnum(32);
                $new_file = $up_dir . $name . '.' . $type;
                if(file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_img)))){
                    return "/uploads/" . date('Ymd', time()) . "/" . $name . '.' . $type;
                }
            }
        }
        return false;
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar   头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio      个人简介
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $perfect = $this->request->post('perfect');
        // $username = $this->request->post('username');
        $nickname = $this->request->post('nickname');
        $name = $this->request->post('name');
        $age = $this->request->post('age');
        $region = $this->request->post('region');
        $gender = $this->request->post('gender'); //0女 1男 2其他
        $weight = $this->request->post('weight'); //体重
        $notice = $this->request->post('notice');
        $unit = $this->request->post('unit');
        $googleHealth = $this->request->post('googleHealth');
        $tryride = $this->request->post('tryride');
        $agreement = $this->request->post('agreement');
        $bikestatus = $this->request->post('bikestatus');
        // $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        // $bio = $this->request->post('bio');
        if ($perfect) {
            if (!$name || !$age || $gender=='') {
                $this->error(__('Please fill in the information first'));
            }
        }
        // if ($avatar) {
        //     $user->avatar = $avatar;
        // }
        // $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if ($name) {
            $exists = \app\common\model\User::where('name', $name)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('name already exists'));
            }
            $user->name = $name;
        }
        if ($nickname) {
            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Nickname already exists'));
            }
            $user->nickname = $nickname;
        }
        if ($region) {
            $user->region = $region;
        }
        if ($age) {
            $user->age = $age;
        }
        if ($gender!='') {
            $user->gender = $gender;
        }
        if ($weight) {
            $user->weight = $weight;
        }
        if ($notice!='') {
            $user->notice = $notice;
        }
        if ($unit) {
            $user->unit = $unit;
        }
        if ($googleHealth!='') {
            $user->googleHealth = $googleHealth;
        }
        if ($tryride!='') {
            $user->tryride = $tryride;
        }
        if ($agreement!='') {
            $user->agreement = $agreement;
        }
        if ($bikestatus!='') {
            $user->bikestatus = $bikestatus;
        }
        $user->save();
        $this->success(__('Perfect information successfully'));
    }

    public function uploadpushtoken()
    {
        $user = $this->auth->getUser();
        $android_token = $this->request->post('android_token');
        $apple_token = $this->request->post('apple_token');
        if ($android_token!='') {
            $user->android_token = $android_token;
        }
        if ($apple_token!='') {
            $user->apple_token = $apple_token;
        }
        $user->save();
        $this->success(__(''));
    }

    /**
     * 修改邮箱
     *
     * @ApiMethod (POST)
     * @param string $email   邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->post('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * 第三方登录参数获取
     *
     * @ApiMethod (POST)
     * @param string $platform 平台名称
     */
    public function thirdpParameter()
    {
        $data = [
                'iosaudit'=>Config::get('site.iosaudit')
            ];
        $this->success('', $data);
    }

    /**
     * 第三方登录
     *
     * @ApiMethod (POST)
     * @param string $platform 平台名称
     * @param string $code     Code码
     */
    public function third()
    {
        $platform = $this->request->post("platform");
        $id_token = $this->request->post("token");
        $accesstoken = $this->request->post("token");
        switch ($platform) {
            case 'facebook':
                $params = [
                        'fields' => 'id,name,email,picture',
                        'access_token' => $id_token
                ];
                $result = Http::sendRequest("https://graph.facebook.com/me", $params, 'GET');
                if ($result['ret']) {
                    $access = (array)json_decode($result['msg'], true);
                    //halt($access);
                    // if(!isset($access['email'])){
                    //     $this->error(__('Unauthorized email'));
                    // }
                    if(isset($access['id'])){
                            $third = model('app\api\model\qixing\Third')->get(['platform' => 'facebook', 'openid' => $access['id']]);
                            if ($third) {
                                $user = model('app\common\model\User')->get($third['user_id']);
                                if (!$user) {
                                    $this->success('User has not yet been binding', [
                                        'binding' => 0,
                                        'third_id' => $third['id']
                                    ]);//尚未绑定用户
                                }
                                $third->save([
                                    'access_token' => $id_token,
                                    'expires_in' => 7776000,
                                    'logintime' => time(),
                                    'expiretime' => time()+7776000
                                ]);
                                $ret = $this->auth->direct($third['user_id']);
                                if ($ret) {
                                    // if (isset($client_id) && $client_id != null) {
                                        //$this->wanlchat->bind($client_id, $this->auth->id);
                                    // }
                                    $data = ['userinfo' => $this->auth->getUserinfo(),'new'=>0];
                                    $this->success(__('Logged in successful'), $data);
                                } else {
                                    $this->error($this->auth->getError());
                                }
                            }else{
                                // 新增$third
                                $third = model('app\api\model\qixing\Third');
                                $third->platform  = 'facebook';
                                $third->openid  = $access['id'];
                                $third->access_token  = $id_token;
                                $third->expires_in  = 7776000;
                                $third->logintime  = time();
                                $third->expiretime  = time() + 7776000;
                                // 获取到的用户信息
                                if (isset($access['email'])) {
                                    $user = \app\common\model\User::getByEmail($access['email']);
                                }else{
                                    $user = false;
                                }
                                
                                if($user){
                                    //有账号直接登录
                                    $ret = $this->auth->direct($user->id);
                                    // 更新第三方登录
                                    $third->user_id  = $this->auth->id;
                                    $third->save();
                                    $data = ['userinfo' => $this->auth->getUserinfo(),'new'=>0];
                                    $this->success(__('Logged in successful'), $data);
                                }else{
                                   // 注册账户
                                   if (isset($access['email'])) {
                                       $result = $this->auth->register($access['email'], Random::alnum(), $access['email'],'');
                                   }else{
                                        $result = $this->auth->register($access['name'].Random::alnum(), Random::alnum(), '','');
                                   }
                                   
                                   if ($result) {
                                        // if (isset($client_id) && $client_id != null) {
                                            //$this->wanlchat->bind($client_id, $this->auth->id);
                                        // }
                                        if (isset($access['name'])&&!empty($access['name'])) {
                                            $user = $this->auth->getUser();
                                            $user->name = $access['name'];
                                            $user->avatar = $access['picture']['data']['url'];
                                            $user->save();
                                        }
                                        // 更新第三方登录
                                        $third->user_id  = $this->auth->id;
                                        $third->save();
                                        $data = ['userinfo' => $this->auth->getUserinfo(),'new'=>1];
                                        $this->success(__('Sign up successful'), $data);
                                    } else {
                                        $this->error($this->auth->getError());
                                    }
                                }
                            }

                        }else{
                            $this->error($access['error_description']);
                        }
                    }else{
                        $err = json_encode($result['msg']);
                        $this->error($err);
                    }
                break;
            case 'google':

                    $params = [
                        'id_token' => $id_token
                    ];
                    $result = Http::sendRequest("https://oauth2.googleapis.com/tokeninfo", $params, 'GET');
                    if ($result['ret']) {
                        $access = (array)json_decode($result['msg'], true);
                        if(!isset($access['email'])){
                            $this->error(__('Unauthorized email'));
                        }
                        if(isset($access['sub'])){
                            $third = model('app\api\model\qixing\Third')->get(['platform' => 'google', 'openid' => $access['sub']]);
                            if ($third) {
                                $user = model('app\common\model\User')->get($third['user_id']);
                                if (!$user) {
                                    $this->success('User has not yet been binding', [
                                        'binding' => 0,
                                        'third_id' => $third['id']
                                    ]);//尚未绑定用户
                                }
                                $third->save([
                                    'access_token' => $id_token,
                                    'expires_in' => 7776000,
                                    'logintime' => time(),
                                    'expiretime' => time()+7776000
                                ]);
                                $ret = $this->auth->direct($third['user_id']);
                                if ($ret) {
                                    // if (isset($client_id) && $client_id != null) {
                                        //$this->wanlchat->bind($client_id, $this->auth->id);
                                    // }
                                    $data = ['userinfo' => $this->auth->getUserinfo(),'new'=>0];
                                    $this->success(__('Logged in successful'), $data);
                                } else {
                                    $this->error($this->auth->getError());
                                }
                            }else{
                                // 新增$third
                                $third = model('app\api\model\qixing\Third');
                                $third->platform  = 'google';
                                $third->openid  = $access['sub'];
                                $third->access_token  = $id_token;
                                $third->expires_in  = 7776000;
                                $third->logintime  = time();
                                $third->expiretime  = time() + 7776000;
                                // 获取到的用户信息
                                $user = \app\common\model\User::getByEmail($access['email']);
                                if($user){
                                    //有账号直接登录
                                    $ret = $this->auth->direct($user->id);
                                    // 更新第三方登录
                                    $third->user_id  = $this->auth->id;
                                    $third->save();
                                    $data = ['userinfo' => $this->auth->getUserinfo(),'new'=>0];
                                    $this->success(__('Logged in successful'), $data);
                                }else{
                                   // 注册账户
                                   $result = $this->auth->register($access['email'], Random::alnum(), $access['email'],'');
                                   if ($result) {
                                        // if (isset($client_id) && $client_id != null) {
                                            //$this->wanlchat->bind($client_id, $this->auth->id);
                                        // }
                                        if (isset($access['name'])&&!empty($access['name'])) {
                                            $user = $this->auth->getUser();
                                            $user->name = $access['name'];
                                            $user->avatar = $access['picture'];
                                            $user->save();
                                        }
                                        // 更新第三方登录
                                        $third->user_id  = $this->auth->id;
                                        $third->save();
                                        $data = ['userinfo' => $this->auth->getUserinfo(),'new'=>1];
                                        $this->success(__('Sign up successful'), $data);
                                    } else {
                                        $this->error($this->auth->getError());
                                    }
                                }
                            }

                        }else{
                            $this->error($access['error_description']);
                        }
                    }else{
                        $err = (array)json_decode($result['msg'], true);
                        $this->error($err['error_description']);
                    }
                break;
            default:
                // code...
                break;
            }

    }
     /**
     * 佣金规则
     *
     * @ApiMethod (POST)
     */
    public function bonus()
    {
        $userid = $this->auth->id;
        $data = [
            'bonustxt' => html_entity_decode(htmlspecialchars_decode(Config::get('site.bonus'))),
            'commission' => Db::name('user')->where(['id'=>$userid])->value('commission'),
         ];
        $this->success('',$data);
    }
    /**
     * 个人中心
     *
     * @ApiMethod (POST)
     */
    public function center()
    {
        $userid = $this->auth->id;
        $eid = $this->request->post("eid");
        $userinfo = $this->auth->getUser();
        $userinfo['level_text'] = Db::name('user_level')->where('id',$userinfo['level'])->value('level_text');
        $userinfo['level_content'] = html_entity_decode(htmlspecialchars_decode(Db::name('user_level')->where('id',$userinfo['level'])->value('level_content')));
        $userinfo['level_icon'] = cdnurl(Db::name('user_level')->where('id',$userinfo['level'])->value('level_icon'),true);
        $equipment = [];
        if ($eid) {
            Db::name('user')->where('id',$userid)->update(['deviceid'=>$eid]);
            $equipment = Db::name('equipment')->where(['id'=>$eid])->whereNull('deleteTime')->find();
        }else{
            $usere = Db::name('user_equipment')->where('userid',$userid)->whereNull('deleteTime')->find();
            $equipid = isset($usere['equipmentid'])?$usere['equipmentid']:0;
            $equipment = Db::name('equipment')->where(['id'=>$equipid])->order('createtime desc')->find();
            
        }
        if (isset($equipment['totalmileage'])) {
            $equipment['totalmileage'] = $equipment['totalmileage']>0?floatval(sprintf('%.1f',$equipment['totalmileage']/10)):0;
        }
        $todayArr=[];
        //当日骑行距离km
        $todaydistance = Db::name('cycling')->where('userid',$userid)->whereTime('createtime','today')->sum('actualdistance');
        //$todaydistance = $todaydistance>=100?floatval(sprintf('%.1f',$todaydistance/1000)).'km':floatval($todaydistance).'m';
        $todaytj = Config::get('site.todaytj');
        $todayArr['todaytj'] = $todaytj?intval($todaytj):5000;//每日推荐骑行距离
        $todayArr['todaytjval'] = floatval(sprintf('%.1f',$todayArr['todaytj']*0.00062137)).'miles';//每日推荐固定5km
        $todayArr['todaydistance'] = $todaydistance;
        $todayArr['todaydistanceval'] = $todaydistance>60 ? floatval(sprintf('%.1f',$todaydistance*0.00062137)).'miles':'0.0miles';
        //1=达标 2=未达标
        if ($todaydistance>=intval($todayArr['todaytj'])) {
            $todayArr['complete'] = 1;

        }else{
            $todayArr['complete'] = 2;
        }
        //试骑
        $tryride = [];
        $whereOr = ['applyuid'=>$userid,'status'=>['in','0,1']];
        $tryride = Db::name('tryride')->where(['touid'=>$userid,'tostatus'=>['in','0']])
        ->whereNull('deletetime')
        ->whereOr(function ($query) use ($whereOr) {
            $query->where($whereOr);
        })
        ->order('id desc')->find();
        $tryridenum = Db::name('tryride')->where(['touid'=>$userid,'tostatus'=>['in','0']])
        ->whereNull('deletetime')
        ->whereOr(function ($query) use ($whereOr) {
            $query->where($whereOr);
        })->value('count(*)');
        $sq = true;
        if ($tryride) {
            if ($tryride['applyuid']==$userid) {
                $user = Db::name('user')->where(['id'=>$tryride['touid']])->find();
                $tryride['avatar'] = '';
                if (isset($user['avatar'])&&$user['avatar']) {
                    $str="/http[s]?:\\/\\/[\\w.]+[\\w\\/]*[\\w.]*\\??[\\w=&\\+\\%]*/is";
                    if(preg_match($str, $user['avatar']))
                    { 
                        $tryride['avatar'] = $user['avatar'];
                    }else{
                        $tryride['avatar'] =  cdnurl($user['avatar'],true);
                    }
                    
                }
                
                $tryride['nickname'] = isset($user['name'])?$user['name']:'';
                $tryride['gender'] = isset($user['gender'])&&$user['gender']==0?lang('Woman'):lang('Man');
                $tryride['region'] = isset($user['region'])&&$user['region']?$user['region']:'';
                $tryride['mobile'] = isset($tryride['tomobile'])&&$tryride['tomobile']?$tryride['tomobile']:'';
                $tryride['address'] = isset($tryride['toaddress'])&&$tryride['toaddress']?$tryride['toaddress']:'';
                $tryride['cstatus'] = isset($tryride['applystatus'])&&$tryride['applystatus']?$tryride['applystatus']:0;

            }else{
                $sq = false;
                $user = Db::name('user')->where(['id'=>$tryride['applyuid']])->find();
                $tryride['avatar'] = '';
                if (isset($user['avatar'])&&$user['avatar']) {
                    $str="/http[s]?:\\/\\/[\\w.]+[\\w\\/]*[\\w.]*\\??[\\w=&\\+\\%]*/is";
                    if(preg_match($str, $user['avatar']))
                    { 
                        $tryride['avatar'] = $user['avatar'];
                    }else{
                        $tryride['avatar'] =  cdnurl($user['avatar'],true);
                    }
                }
                $tryride['nickname'] = isset($user['name'])?$user['name']:'';
                $tryride['gender'] = isset($user['gender'])&&$user['gender']==0?lang('Woman'):lang('Man');
                $tryride['region'] = isset($user['region'])&&$user['region']?$user['region']:'';
                $tryride['mobile'] = isset($tryride['applymobile'])&&$tryride['applymobile']?$tryride['applymobile']:'';
                $tryride['address'] = isset($tryride['applyaddress'])&&$tryride['applyaddress']?$tryride['applyaddress']:'';
                $tryride['cstatus'] = isset($tryride['tostatus'])&&$tryride['tostatus']?$tryride['tostatus']:0;
            }
            if (!$sq) {
                $issqr = 2;
            }else{
                $issqr = 1;
            }
            $tryride['issqr'] = $issqr;
            $endtime = strtotime($tryride['startTime'])+$tryride['time_unit'];
            $tryride['userendtime'] = date('Y-m-d H:i:s',$endtime);
            $tryride['isend'] = $endtime>time()?0:1;
        }
        if (isset($equipment['id'])) {
            $usere = Db::name('user_equipment')->where(['userid'=>$userinfo['id'],'equipmentid' => $equipment['id']])
            ->whereNull('deleteTime')
            ->find();
        }else{
            $usere = [];
        }
        
        if(!isset($equipment['sn_mac']) && isset($equipment['sn'])){
            $equipment['sn_mac'] = sn_mac($equipment['sn']);
        }
        if($usere){
            $equipment['name'] = $usere['bname'];
        }
        if(isset($equipment['danci'])&&!empty($equipment['danci'])){

            $equipment['danci'] = ($equipment['danci']/10)+0;
        }
        $agreement = [
            'str' => Config::get(lang('agreement'))
        ];
        $data = ['userinfo' => $userinfo,'equipment'=>$equipment,'todayArr'=>$todayArr,'tryride'=>$tryride,'tryridenum'=>$tryridenum,'agreement'=>$agreement];
        $this->success(__(''), $data);
    }
    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetpwd()
    {
        // $type = $this->request->post("type");
        $type = 'email';
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email");
        $newpassword = $this->request->post("newpassword");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 修改密码
     *
     * @ApiMethod (POST)
     * @param string $password 原密码
     * @param string $newpassword 新密码
     */
    public function modifypwd()
    {
        // $type = $this->request->post("type");
        $user = $this->auth->getUser();
        $password = $this->request->post("password");
        $newpassword = $this->request->post("newpassword");
        if (!$password || !$newpassword) {
            $this->error(__('Invalid parameters'));
        }
        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }
        if ($user->password != $this->auth->getEncryptPassword($password, $user->salt)) {
            $this->error(__('Original password is incorrect'));
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 个人信息 用户信息
     */
    public function userInfo()
    {
        $userinfo = $this->auth->getUser();
        $userinfo['fullavatar'] = $userinfo['avatar'];
        $userinfo['unit'] = $userinfo['unit']?$userinfo['unit']:'mi';
        $data = ['userinfo' => $userinfo];
        $this->success(__(''), $data);
    }

    /**
     * location地址信息
     */
    public function locationinfo()
    {
        $language = explode(',',$_SERVER['HTTP_ACCEPT_LANGUAGE']);
        $data = [];
        if($language[0]=='en'){
            $data = json_decode(stripslashes(file_get_contents(ROOT_PATH.'public/assets/location_en.json')),true);
        }elseif($language[0]=='es'){
            $data = json_decode(stripslashes(file_get_contents(ROOT_PATH.'public/assets/location_es.json')),true);
        }else{
            $data = json_decode(stripslashes(file_get_contents(ROOT_PATH.'public/assets/location_zh.json')),true);
        }
        //只显示美国
        $american = $data['Location']['regioncolumns'][0]['children'];
        $data['Location']['regioncolumns'] = [];
        $data['Location']['regioncolumns'][0] = $american;
        $this->success(__(''), $data);
    }

    /**
     * location筛选地址信息
     */
    public function locationscreening()
    {
        $countiesId = input("countiesId");
        $provinceId = input("provinceId");
        $language = explode(',',$_SERVER['HTTP_ACCEPT_LANGUAGE']);
        if($language[0]=='en'){
            $jdata = json_decode(stripslashes(file_get_contents(ROOT_PATH.'public/assets/location_en.json')),true);
        }else{
            $jdata = json_decode(stripslashes(file_get_contents(ROOT_PATH.'public/assets/location_zh.json')),true);
        }
        $jdata = $jdata['Location']['regioncolumns'];
        $counties = [];
        $province = [];
        $city = [];
        foreach ($jdata as $key => $vs) {
            if (!$countiesId) {
                $counties[$key]['id'] = intval($key)+1;
                $counties[$key]['text'] = $vs['text'];
                $counties[$key]['code'] = $vs['code'];
            }
            if (isset($vs['children'])) {
                foreach ($vs['children'] as $key2 => $vs2) {
                    if (isset($vs2['text'])&&$countiesId>0&&!$provinceId&&$countiesId == intval($key)+1) {
                            $province[$key2]['countiesId'] = intval($key)+1;
                            $province[$key2]['provinceId'] = intval($key2)+1;
                            $province[$key2]['text'] = $vs2['text'];
                            $province[$key2]['code'] = $vs2['code'];
                    }
                    
                    if (isset($vs2['children'])) {
                        foreach ($vs2['children'] as $key3 => &$vs3) {
                            if (is_array($vs3)) {
                                if ($countiesId>0 && $provinceId>0&&$provinceId == intval($key2)+1) {
                                        $city[$key3]['countiesId'] = intval($key)+1;
                                        $city[$key3]['provinceId'] = intval($key2)+1;
                                        $city[$key3]['cityId'] = intval($key3)+1;
                                        $city[$key3]['text'] = $vs3['text'];
                                        $city[$key3]['code'] = $vs3['code'];
                                }
                                
                            }
                            
                        }
                    }
                    
                }
            }
        }
        $data = [
            'counties' => $counties,
            'province' => $province,
            'city' => $city
        ];
        
        $this->success(__(''), $data);
    }



    /**
     * 个人 使用帮助
     */
    public function usehelp()
    {
        $params = $this->request->post();
        $page = isset($params['page']) ? $params['page'] : 1;
        $pageSize = isset($params['pageSize']) ? $params['pageSize'] : 10;
        $key = $this->request->post('key');
        $where = [];
        $where['status'] = 1;
        if ($key) {
            $where['title'] = ['like','%'.$key.'%'];
        }
        $list = Db::name('user_help')
        ->where($where)
        ->where('deleteTime is null')
        ->limit(($page - 1)*$pageSize,$pageSize)
        ->select();
        $data = [
                    'list'  => $list
                ];
        $this->success(__(''), $data);
    }

    /**
     * 个人 使用帮助详情
     */
    public function usehelpDetail()
    {
        $id = $this->request->post('id');
        if (!$id) {
            $this->error(__('Invalid parameters'));
        }
        $where = [];
        $where['id'] = $id;
        $detail = Db::name('user_help')
        ->where($where)
        ->find();
        $data = [
                    'detail'  => $detail
                ];
        $this->success(__(''), $data);
    }

    /**
     * health数据设置
     */
    public function HealthConfig()
    {
        $healthday = Config::get('site.healthday');
        $data = [
                    'day'  => $healthday?$healthday:7
                ];
        $this->success(__(''), $data);
    }

    /**
     * 同步google health数据
     */
    public function googleHealth()
    {
        $userid = $this->auth->id;
        $json = $this->request->post('json');
        if (!$json) {
            $this->error(__('Invalid parameters'));
        }
        $heart = json_decode(html_entity_decode(htmlspecialchars_decode(stripslashes($json))),true);
        $where = [];
        $where['userid'] = $userid;
        $health = Db::name('user_health')->where('userid',$userid)->find();
        if ($health) {
            Db::name('user_health')->where('userid',$userid)->update(['json'=>json_encode($heart)]);
        }else{
            Db::name('user_health')->insert(['userid'=>$userid,'json'=>json_encode($heart),'createtime'=>date('Y-m-d H:i:s',time())]);
        }
        $this->success(__('Data synchronization into!'));
    }

    /**
     * google health数据接口
     */
    public function healthData()
    {
        $userid = $this->auth->id;
        $health = json_decode(Db::name('user_health')->where('userid',$userid)->value('json'),true);
        $sleeparr = [];//睡眠分数
        $mileagearr = [];//里程
        $hrvarr = [];//hrv
        $day = [];
        $status = 1;
        if (isset($health['sleep'])&&isset($health['heart'])) {
            if (count($health['sleep'])==0&&count($health['heart'])==0 ) {
                $status = 0;
            }
        }
        
        //循环7数据
        for ($i=0; $i<7 ; $i++) {
            $day[$i] = date('n.j',strtotime('-'.(7-$i).' day'));
            $sday = date('Y-m-d',strtotime('-'.(7-$i).' day'));
            $sleep = isset($health['sleep'])?$health['sleep']:[];
            //type 0=卧床 1=睡眠 2=清醒时间 3=核心睡眠 4=深度睡眠 5=快速眼动睡眠
            $sleepscore = 0;//睡眠分数
            $sdtart = 0;
            $sdtdua = 0;
            $thirdcore = 0;
            $twofours = false;
            $ttype = true;
            $sleeptime = 0;
            if ($sleep) {
                foreach ($sleep as $vv) {
                    if ($vv['type']!=6) {//排除不睡眠状态
                        $start = date('n.j',$vv['start']);
                        if ($start==$day[$i]) {
                            
                            if ($vv['type']==1) {
                                $wotime = intval(($vv['start']+$vv['end'])/2);
                                $ghours = date('Gi',$wotime);
                                if (intval($ghours)<200 && intval($ghours)>400) {//睡眠时间凌晨2点-4点
                                    $twofours = true;
                                }
                                $sleeptime = $sleeptime+$vv['end']-$vv['start'];//睡眠时间

                                if ($sdtart>0) {
                                    $sdtdua = $sdtart-$vv['start'];
                                }else{
                                    $sdtart = $vv['start'];
                                }
                                if ($sdtdua<1800) {
                                    $thirdcore = 1;
                                }else{
                                    $thirdcore = 0;
                                }
                                $ttype = false;
                                //var_dump('6.4-'.$ghours);
                                //var_dump('6.4-'.$sleeptime);
                            }
                            
                            
                        }
                        
                    }

                }
                if ($ttype) {
                    foreach ($sleep as $vv) {
                        if ($vv['type']!=6) {//排除不睡眠状态
                            $start = date('n.j',$vv['start']);
                            if ($start==$day[$i]) {
                                
                                if ($vv['type']==0) {
                                    $wotime = intval(($vv['start']+$vv['end'])/2);
                                    $ghours = date('Gi',$wotime);
                                    if (intval($ghours)<200 && intval($ghours)>400) {//睡眠时间凌晨2点-4点
                                        $twofours = true;
                                    }
                                    $sleeptime = $sleeptime+$vv['end']-$vv['start'];//睡眠时间

                                    if ($sdtart>0) {
                                        $sdtdua = $sdtart-$vv['start'];
                                    }else{
                                        $sdtart = $vv['start'];
                                    }
                                    if ($sdtdua>1800) {
                                        $thirdcore = 0;
                                    }
                                    $ttype = false;
                                }
                                
                                
                            }
                            
                        }

                    }
                }
                if ($twofours) {
                    $sleepscore++;
                }
                if ($sleeptime>=21600 && $sleeptime<=28800) {//睡眠时长6小时-8小时
                    $sleepscore++;
                }
                
            }
            $hrv = isset($health['heart'])?$health['heart']:[];
            $hearnum = 0;
            $num = 0;
            if ($hrv) {
                foreach ($hrv as $vs) {
                    $start = date('n.j',$vs['start']);
                    if ($start==$day[$i]) {
                        $num++;
                        $hearnum = $hearnum + $vs['value'];
                    }
                }
            }
            $mileage = Db::name('cycling')->where('userid',$userid)->where('createtime','like','%'.$sday.'%')->sum('actualdistance');
            $mileagearr[$i] = $mileage>100 ? floatval(sprintf('%.1f',$mileage*0.00062137)):0;
            $sleeparr[$i] = $sleepscore;
            $hrvarr[$i] = $hearnum>0&&$num>0?floatval(sprintf('%.1f',$hearnum/$num)):0;
        }

        if ($thirdcore==1) { //SRI计算
            foreach ($sleeparr as &$value) {
                $value = $value+1;
            }
            unset($value);
        }

        $data['data1']=[
            'txt' => [lang('Sleep score'), lang('Mileage')],
            'sleep' => [
                'd1'=>$sleeparr,
                'd2'=>$day
            ],
            'mileage'=>[
                'd1'=>$mileagearr,
                'd2'=>$day
            ]
        ];
        $data['data2']=[
            'txt' => [lang('HRV'), lang('Mileage')],
            'hrv' => [
                'd1'=>$hrvarr,
                'd2'=>$day
            ],
            'mileage'=>[
                'd1'=>$mileagearr,
                'd2'=>$day
            ]
        ];
        $data['data3']=[
            'txt' => [lang('Sleep score'), lang('HRV')],
            'sleep' => [
                'd1'=>$sleeparr,
                'd2'=>$mileagearr
            ],
            'hrv' => [
                'd1'=>$hrvarr,
                'd2'=>$mileagearr
            ]
        ];
        $data['status'] = $status;
        $this->success(__(''), $data);
    }

    /**
     * 勋章接口
     */
    public function medal()
    {
        $user = $this->auth->getUser();
        $medal = [];
        $medalLevel = [];
        $medal['medaltitle'] = Config::get('site.medaltitle');
        $medal['medalcontent'] = Config::get('site.medalcontent');
        if ($user['level']) {
            $medalLevel = Db::name('user_level')->where('id',$user['level'])->find();
        }else{
            $medalLevel = Db::name('user_level')->order('totaldistance asc')->find();
        }
        $str="/http[s]?:\\/\\/[\\w.]+[\\w\\/]*[\\w.]*\\??[\\w=&\\+\\%]*/is";
        if(preg_match($str, $user['avatar']))
        { 
            $user['fullavatar'] = $user['avatar'];
        }else{
            $user['fullavatar'] = $user['avatar']?cdnurl($user['avatar'], true):cdnurl('/assets/img/avatar2.png', true);
        }
        $medalLevel['level_content'] = html_entity_decode(htmlspecialchars_decode($medalLevel['level_content']));
        $medalLevel['level_icon'] = cdnurl($medalLevel['level_icon'],true);
        $data = ['user'=>$user,'medal'=>$medal,'medalLevel'=>$medalLevel];
        $this->success(__(''), $data);
    }

}
